﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace FBGraph.ClientGenerator.Documentation
{
    public class TypeDocumentation
    {
        private TypeDocumentation(String path)
        {
            this.Document = XDocument.Load(path);

            this.Items = (
                from item in this.Document.Descendants("item")
                select new { Cref = item.Attribute("cref").Value, Elements = item.Elements() })
                    .ToDictionary(item => item.Cref, item => item.Elements);
        }

        private XDocument Document { get; set; }
        private Dictionary<String, IEnumerable<XElement>> Items { get; set; }

        public Boolean HasDocumentationFor(String cref) { return this.Items.ContainsKey(cref); }
        public String[] GetDocumentation(String cref)
        {
            var items = this.Items[cref];

            var builder = new StringBuilder();
            using (var writer = XmlWriter.Create(builder, new XmlWriterSettings { OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment }))
            {
                foreach (var item in items)
                {
                    item.WriteTo(writer);
                }
                writer.Flush();
            }

            return builder.ToString().Split(new String[] { Environment.NewLine }, StringSplitOptions.None);
        }

        public static TypeDocumentation Load(String path)
        {
            return new TypeDocumentation(path);
        }
    }
}